import React, { useEffect } from "react";
import style from "../../style/Warehousemanage.module.scss";
import { Link, Route } from "react-router-dom";
import { renderRoutes } from "react-router-config";
import { Input, Select, Space, Button, Table } from "antd";
import { useCallback, useState, useRef } from "react";
import { getAll } from "../../api/warehouse";

function WarehousemanageContent() {
  const [search, setsearch] = useState(""); //搜索
  const [name, setname] = useState(""); //仓库名称
  const [address, setaddress] = useState(""); //仓库地址
  const [city, setcity] = useState(""); //所在城市
  const [aaaa, setaaaa] = useState(""); //所在区域
  const [area1, set1area] = useState(""); //仓库面积1
  const [area2, set2area] = useState(""); //仓库面积2

  const NameRef = useRef(); //仓库名称
  const area1Ref = useRef(); //仓库面积1
  const area2Ref = useRef(); //仓库面积2

  const Area1Action = useCallback(() => {
    set1area(area1Ref.current.input.value);
  }, []);

  const Area2Action = useCallback(() => {
    set2area(area2Ref.current.input.value);
  }, []);

  const nameAction = useCallback(() => {
    setname(NameRef.current.input.value);
    // console.log(NameRef.current.input.value);
  }, []);

  const onChangeCity = useCallback((value) => {
    setcity(value);
    console.log(`${value}`);
  }, []);
  //城市选择器中选择的选项
  const onSearchCity = useCallback((value) => {
    console.log(value);
  }, []);
  //城市选择器中搜索的文字
  const onChangeArea = useCallback((value) => {
    setaaaa(value);
    console.log(`${value}`);
  }, []);
  //区域选择器中选择的选项
  const onSearchArea = useCallback((value) => {
    console.log(value);
  }, []);
  //区域选择器中搜索的文字

  //查询功能
  const SreachAction = useCallback(() => {
    let aaa = ""; //查询出的数据暂存在aaa
    //判断id/用户名/手机号
    if (name) {
      // console.log(name);
      const res = data.filter(
        (item) => item.name === name || item.address === name
      );
      setsearch(res);
      aaa = res;
      console.log(aaa);
    }
    if (area1 && area2) {
      // console.log(area1, area2);
      const res = (aaa ? aaa : data).filter(
        (item) =>
          // console.log(item)
          item.area >= area1 && item.area <= area2
      );
      setsearch(res);
      aaa = res;
    }
    if (city) {
      // console.log(city);
      const res = (aaa ? aaa : data).filter((item) => item.city === city);
      setsearch(res);
      aaa = res;
      console.log();
    }
    if (aaaa) {
      // console.log(city);
      const res = (aaa ? aaa : data).filter((item) => item.region === aaaa);
      setsearch(res);
      aaa = res;
      console.log(res);
    } else {
      return;
    }
  }, [name, area1, area2, city, aaaa, search]);

  //重置功能
  const resetAction = useCallback(() => {
    setsearch("");
  }, []);

  /* ----------------------------引用table组--------------------------- */
  const columns = [
    {
      title: "仓库名称",
      dataIndex: "name",
      render: (name) => `${name}`,
    },
    {
      title: "所在城市",
      dataIndex: "city",
      render: (city) => `${city}`,
      width: "20%",
    },
    {
      title: "所在区域",
      dataIndex: "region",
      render: (region) => `${region}`,
    },
    {
      title: "仓库地址",
      dataIndex: "address",
      render: (address) => `${address}`,
    },
    {
      title: "区域面积（㎡）",
      dataIndex: "area",
      render: (area) => `${area}`,
    },
    {
      title: "操作",
      key: "operate",
      render: () => (
        <Space size="middle">
          <a>仓库详情</a>
          <a>停用</a>
        </Space>
      ),
    },
  ];
  const getRandomuserParams = (params) => ({
    results: params.pagination?.pageSize,
    page: params.pagination?.current,
    ...params,
  });

  const [data, setData] = useState();
  const [loading, setLoading] = useState(false);
  const [tableParams, setTableParams] = useState({
    pagination: {
      current: 1,
      pageSize: 10,
    },
  });
  useEffect(() => {
    fetchData();
  }, [search]);
  const fetchData = async () => {
    await getRandomuserParams(tableParams);
    try {
      const results = await getAll();
      console.log(results.data.msg);
      setLoading(true);
      setData(results.data.msg);

      setLoading(false);
      setTableParams({
        ...tableParams,
        pagination: {
          ...tableParams.pagination,
          total: data,
        },
      });
      console.log(data);
    } catch (error) {
      console.log(error);
    }
  };

  const handleTableChange = (pagination, filters, sorter) => {
    setTableParams({
      pagination,
      filters,
      ...sorter,
    });

    // `dataSource` is useless since `pageSize` changed
    if (pagination.pageSize !== tableParams.pagination?.pageSize) {
      setData([]);
    }
  };
  /* ------------------------------------------------------------ */

  return (
    <div className={style.Dashboard}>
      <div className={style.box}>
        <div className="first">
          <Input
            placeholder=" 仓库名称/仓库地址"
            ref={NameRef}
            onChange={nameAction}
            style={{ width: "40vh", margin: "20px 0px 20px 20px " }}
          />
          {/* 仓库名称输入框 */}
          <Select
            showSearch
            placeholder="所在城市"
            optionFilterProp="children"
            style={{ width: "20vh", margin: "20px 0px 20px 20px " }}
            onChange={onChangeCity}
            onSearch={onSearchCity}
            filterOption={(input, option) =>
              (option?.label ?? "").toLowerCase().includes(input.toLowerCase())
            }
            options={[
              {
                value: "北京",
                label: "北京",
              },
              {
                value: "上海",
                label: "上海",
              },
              {
                value: "广州",
                label: "广州",
              },
              {
                value: "深圳",
                label: "深圳",
              },
            ]}
          />
          {/* 所在城市选择框 */}
          <Select
            showSearch
            placeholder="所在区域"
            optionFilterProp="children"
            style={{ width: "20vh", margin: "20px 0px 20px 20px " }}
            onChange={onChangeArea}
            onSearch={onSearchArea}
            filterOption={(input, option) =>
              (option?.label ?? "").toLowerCase().includes(input.toLowerCase())
            }
            options={[
              {
                value: "老区",
                label: "老区",
              },
              {
                value: "新区",
                label: "新区",
              },
            ]}
          />
          {/* 所在区域选择框 */}
          <Space.Compact
            className="Warehouse"
            size="middle"
            style={{ width: "30vh", margin: "20px 0px 20px 20px " }}
          >
            <Input
              placeholder="仓库面积"
              ref={area1Ref}
              onChange={Area1Action}
            />
            <Input
              placeholder="仓库面积"
              ref={area2Ref}
              onChange={Area2Action}
            />
          </Space.Compact>
          {/* 仓库面积输入框 */}
        </div>
        <div className="second">
          <Space.Compact
            className="Associated"
            size="middle"
            style={{ width: "40vh", margin: "0px 0px 20px 20px " }}
          >
            <Input placeholder="关联小区数" />
            <Input placeholder="关联小区数" />
          </Space.Compact>
          {/* 关联小区输入框 */}
          <Space.Compact
            className="rider"
            size="middle"
            style={{ width: "30vh", margin: "0px 0px 20px 20px " }}
          >
            <Input placeholder="骑手数" />
            <Input placeholder="骑手数" />
          </Space.Compact>
          {/* 骑手数输入框 */}
          <Space.Compact
            className="Sorting"
            size="middle"
            style={{ width: "40vh", margin: "0px 0px 20px 20px " }}
          >
            <Input placeholder="分拣员" />
            <Input placeholder="分拣员" />
          </Space.Compact>
          {/* 分拣员数输入框 */}
          <Button
            type="primary"
            onClick={SreachAction}
            style={{ backgroundColor: "#666666", margin: "0 0 0 20px " }}
          >
            查询
          </Button>
          <Button onClick={resetAction} style={{ margin: "10px" }}>
            重置
          </Button>
        </div>
        <div className={style.third}>
          <span>查询结果:共计 4 条数据</span>
          <Link to="/warehosemanage/warehouseAdd">
            <Button
              type="primary"
              style={{ backgroundColor: "#666666", margin: "0 0 0 20px " }}
            >
              新增仓库
            </Button>
          </Link>
        </div>
        <Table
          columns={columns}
          rowKey={({ _id }) => _id}
          dataSource={search ? search : data}
          pagination={tableParams.pagination}
          loading={loading}
          onChange={handleTableChange}
        />
      </div>
    </div>
  );
}

export default function Warehousemanage({ route: { routes } }) {
  console.log(routes);
  return (
    <>
      <Route exact path="/warehosemanage" component={WarehousemanageContent} />
      {/* 
      <Switch>
        <Route path="/product/manager/add" component={Add} />
      </Switch>
     */}
      {renderRoutes(routes)}
    </>
  );
}
